package org.example.algorithm.trie;

/**
 * 208. 实现 Trie (前缀树)
 */

public class TrieSolution {
    private TrieSolution[] children;
    private Boolean isEnd;

    public TrieSolution() {
        this.children = new TrieSolution[26];
        this.isEnd = false;
    }

    public void insert(String word) {
        TrieSolution node = this;
        for (int i=0;i<word.length();i++) {
            int index = word.charAt(i) - 'a';
            if (node.children[index] == null) {
                node.children[index] = new TrieSolution();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        TrieSolution node = searchPrefix(word);
        return node != null && node.isEnd;

    }

    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    public TrieSolution searchPrefix(String prefix) {
        TrieSolution node = this;
        for (int i=0;i<prefix.length();i++) {
            int index = prefix.charAt(i) - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}
